package com.aquarium.bt;

import java.util.Timer;
import java.util.TimerTask;

import android.util.Log;

import com.aquarium.config.AlarmDefaultValue;
import com.aquarium.config.BTDataConfig;

public class BTManager {
	private static BTManager mBTManager;
	private RecvDataDispatcher mRecvDataDispatcher;
	// test code
	private Timer mSendSensorValueTimer;

	private BTManager() {
		mRecvDataDispatcher = RecvDataDispatcher.getInstance();
	}

	public static BTManager getInstance() {
		if (mBTManager == null) {
			mBTManager = new BTManager();
		}
		return mBTManager;
	}

	/**
	 * 负责连接到remote BT device
	 */
	public void connect() {
		// TODO
	}

	/**
	 * 发送数据或命令
	 * 
	 * @param data
	 *            所发送的数据
	 */
	private void sendData(DataStruct data) {
		// TODO
	}

	/**
	 * test code
	 */
	public void sendSensorValueTest() {
		if (mSendSensorValueTimer != null) {
			mSendSensorValueTimer.cancel();
		}
		mSendSensorValueTimer = new Timer();
		mSendSensorValueTimer.schedule(new TimerTask() {

			@Override
			public void run() {
				DataStruct struct = new DataStruct();
				struct.code = BTDataConfig.RECV_HP_VALUE;
				struct.data = String.valueOf(getRandamFloat(
						AlarmDefaultValue.MINPH - 0.5f,
						AlarmDefaultValue.MAXPH + 0.5f));
				Log.i("BTManager", "data PH = " + struct.data);
				mRecvDataDispatcher.recv(struct);
				struct.code = BTDataConfig.RECV_TEMPERATURE_VALUE;
				struct.data = String.valueOf(getRandamFloat(
						AlarmDefaultValue.MINTEMPERATURE - 20f,
						AlarmDefaultValue.MAXTEMPERATURE + 20f));
				Log.i("BTManager", "data TEMP = " + struct.data);
				mRecvDataDispatcher.recv(struct);
				struct.code = BTDataConfig.RECV_OXYGEN_VALUE;
				struct.data = String.valueOf(getRandamFloat(
						AlarmDefaultValue.MINOxygen - 80f,
						AlarmDefaultValue.MAXOxygen + 80f));
				Log.i("BTManager", "data OXYGEN = " + struct.data);
				mRecvDataDispatcher.recv(struct);
				struct.code = BTDataConfig.RECV_CONDUCTIVITY_VALUE;
				struct.data = String.valueOf(getRandamFloat(
						AlarmDefaultValue.MINConductivity - 0.2f,
						AlarmDefaultValue.MAXConductivity + 0.2f));
				Log.i("BTManager", "data CONDUC = " + struct.data);
				mRecvDataDispatcher.recv(struct);
				struct.code = BTDataConfig.RECV_WATER_LEVEL_VALUE;
				struct.data = String.valueOf(getRandamFloat(
						AlarmDefaultValue.MINWATERLEVEL - 10f,
						AlarmDefaultValue.MAXWATERLEVEL + 20f));
				Log.i("BTManager", "data WATER LEVEL = " + struct.data);
				mRecvDataDispatcher.recv(struct);
			}
		}, 0, 5000);

	}

	/**
	 * test code
	 */
	public void stopSendSensorValueTest() {
		if (mSendSensorValueTimer == null) {
			return;
		}
		mSendSensorValueTimer.cancel();
	}

	/**
	 * test code
	 * 
	 * @param min
	 * @param max
	 * @return
	 */
	private float getRandamFloat(float min, float max) {

		return (float) (Math.random() * (max - min) + min);
	}
}
